package io.github.yotta.export.web.iface;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import io.github.yotta.common.api.model.ApiPageRequest;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;

/**
 * @author yotta
 * @date 2025/4/26
 */
public class DefaultExportParamConvert<T extends ApiPageRequest> implements ExportParamConvert<T> {

    private static final ObjectMapper mapper = new ObjectMapper();

    static {
        //在反序列化时忽略在 json 中存在但 Java 对象不存在的属性
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //在序列化时日期格式默认为 yyyy-MM-dd'T'HH:mm:ss.SSSZ
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //在序列化时自定义时间日期格式
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //在序列化时忽略值为 null 的属性
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //在序列化时忽略值为默认值的属性
        mapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
        mapper.registerModule(new JavaTimeModule());
        mapper.registerModule(new JodaModule());
    }

    private final Class<T> exportParamClazz;

    public DefaultExportParamConvert(Class<T> exportParamClazz) {
        this.exportParamClazz = exportParamClazz;
    }

    @Override
    public T convert(String exportParamJson) {

        ApiPageRequest exportParam;
        if (StringUtils.isNotEmpty(exportParamJson)) {
            try {
                exportParam = mapper.readValue(exportParamJson, exportParamClazz);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        } else {
            exportParam = new ApiPageRequest();
        }
        return (T) exportParam;
    }
}
